<style>
.layui-table-cell {overflow-x: hidden;overflow: inherit; }
.layui-table-box {
    overflow: inherit;
}
.layui-table-body {
    overflow: inherit;
}

</style>
<div class="fixed-bar">
    <button type="submit" id="addDetail" class="layui-btn" lay-submit="" lay-filter="demo1" >添加退补料</button>
</div>
<table id="dataTable" lay-filter="filterTableSFD"></table>

{include file="system@block/layui" /}

<script type="text/html" id="stallOrderTimeTpl">
    <input type="text" name="stall_order_time" readonly="" style="width: 90px;border: none" id="stall_order_time{{d.id}}" value="{{layui.util.toDateString(d.stall_order_time * 1000, 'yyyy-MM-dd')}}" lay-verify="" class="layui-input stall_order_time" lay-event="stall_order_time" style="border: none">
</script>
<script type="text/html" id="stallIdTpl">
    <div class="stall-select">
    {:Form::select('stall_id','{literal}{{d.stall_id}}{/literal}' , $stallsKV, 'stall-ids-{literal}{{d.id}}{/literal}', 'layui-input','lay-search="" lay-verify="required"')}
    </div>
</script>
<script type="text/html" id="subbtnTpl">
    {{# if(d.status == 1){ }}
        <a class="layui-btn layui-btn-normal layui-btn-xs subbtn-{{ d.id }}" lay-event="save">修改</a>
    {{# }else if(d.status == 0){ }}
        <a class="layui-btn layui-btn-xs subbtn-{{ d.id }}" lay-event="save">确认</a>
    {{# }else if(d.status == 2 || d.status == 3){ }}
       已审核
    {{# } }}

</script>
<script type="text/javascript">
    layui.use(['opTable','table','jquery', 'tool', 'form','laydate', 'layer'], function() {
        var $ = layui.jquery;
        var table = layui.table;
        var form = layui.form;
        var layer = layui.layer;
        var laydate = layui.laydate;
		form.render();
        
        laydate.render({
		    elem: '#caigou_confirm_time'
		    ,range: '~'
		    ,theme: 'molv'
		    ,mark: {'{:$today}':''}
	    	,change: function(value, date, endDate){
		    	$('#caigou_confirm_time').val(value);
            	$('#layui-laydate1').remove();//关闭面板
            }
		});
        
        table.render({
            elem: '#dataTable'
            ,url: "{:url('stallFeedDetail')}?mid={:$mid}" //数据接口
            ,page: true //开启分页
            ,skin: 'row'
            ,even: true
            ,limit: 20
            ,limits: [20,50,100,150,200]
            ,text: {
                none : '暂无相关数据'
            }
            //,toolbar: false
            //,defaultToolbar: ['filter', 'exports', 'print']
            ,cols: [[ //表头
                ,{field:'stall_order_time',title : '供应商单日期',templet: '#stallOrderTimeTpl',width:120}
                ,{field:'stall_order',title : '供应商单号',edit:'text',style:'border-bottom:2px dotted #5FB878;',width:110}
                ,{field:'stall_id',title : '供应商',templet: '#stallIdTpl',width:140}
                ,{field:'billing_caigou_count_feed',title : '开单采购补量',edit:'text',style:'border-bottom:2px dotted #5FB878;',width:120}
                ,{field:'caigou_unitprice',title : '采购单价',edit:'text',style:'border-bottom:2px dotted #5FB878;',width:120}
                ,{field:'billing_caigou_kgcount',title : '开单采购公斤数',edit:'text',style:'border-bottom:2px dotted #5FB878;',width:120}
                ,{field:'billing_caigou_kgprice',title : '开单采购公斤价',edit:'text',style:'border-bottom:2px dotted #5FB878;',width:120}
				,{field:'caigou_amount',title : '采购总金额',width:110} 
                ,{field: 'stall_feed_type', title: '退补类型',edit:'text',style:'border-bottom:2px dotted #5FB878;',width:100}
                
               ,{field:'subbtn', title:'确认', templet:'#subbtnTpl',width:70}
            ]]
            ,done: function (res) {
                var data=res.data,mInfo=res.mInfo;
                for (var i in data){
                    var value=layui.util.toDateString(data[i]['stall_order_time'] * 1000, 'yyyy-MM-dd');
					var nowtime=new Date();
                    if(data[i]['stall_order_time']==0) value=nowtime.getFullYear()+"-"+(nowtime.getMonth()+1)+"-01";
                    laydate.render({
                        elem: "#stall_order_time"+data[i]['id'], //指定元素
                        value: value 
                    });
                    $('#stall-ids-'+data[i]['id']).val(data[i]['stall_id']);
                }
                layui.form.render();
                // 点击补料
                $(document).on('click','#addDetail',function(){
                    var mid={:$mid};            
                    
                    var layerFeed = layer.prompt({title: '请输入数量',id: 'layer-box', formType: 0,success:function(){
                        // 键盘事件，判断回车                       
                        $("input.layui-layer-input").on('keydown',function(e){
                            if (e.which == 13) {
                                feedEvent($(this).val(), mid);
                            }
                        });
                    }}, 
                    function(number,billingCaigouKgcount){
                        feedEvent(number, mid);
                    });
                    if($('#layer-box .billing-caigou-kgcount').length==0) {
                        $('#layer-box').prepend("公斤数：<input class='layui-input billing-caigou-kgcount' type='text' /></br>米数：");
                    }                
                    $(".billing-caigou-kgcount").on("input",function(e){
                        var billingCaigouKgcount=e.delegateTarget.value;
                        var fabricWidth = mInfo.fabric_width;//幅宽
                        var weight = mInfo.weight;//克重
                        var billingCaigouCount = layui.tool.bcdiv((billingCaigouKgcount*100000), fabricWidth*weight);//开单采购总数=(开单采购公斤数*100000)/幅宽 / 克重
                        $('.layui-layer-input').val(billingCaigouCount);
                    });
                    return ;
                });
                table.on('edit(filterTableSFD)', function(obj){
                     var value = obj.value //得到修改后的值
                    ,d = obj.data //得到所在行所有键值
                    ,field = obj.field; //得到字段
                    
                    if (field == 'billing_caigou_kgprice'|| field == 'billing_caigou_kgcount') {
                        var fabricWidth = d.mInfo.fabric_width;//幅宽
                        var weight = d.mInfo.weight;//克重
                        var billingCaigouKgprice = d.billing_caigou_kgprice;//开单采购公斤价
                        var billingCaigouKgcount=d.billing_caigou_kgcount;//开单采购公斤数
                        var caigouUnitprice = layui.tool.bcmul(fabricWidth * weight , billingCaigouKgprice/100000);//单价=幅宽 * 克重 * 开单采购公斤价/100000
                        var billingCaigouCountFeed = layui.tool.bcdiv((billingCaigouKgcount*100000), fabricWidth*weight);//开单采购总数=(开单采购公斤数*100000)/幅宽 / 克重
                        obj.update({caigou_unitprice:caigouUnitprice,billing_caigou_count_feed:billingCaigouCountFeed});
                    }
                });
                //增加新增
                $('.stall-select .layui-anim-upbit').append("<a href='{:url('Stalls/add')}' hisi-data='{}' style='margin-left:15px' class='layui-btn hisi-iframe'>去新增</a>");
            }
        });
        table.on('tool(filterTableSFD)', function(obj){
            var d = obj.data,field=obj.field;
            if(obj.event === 'save'){
                var id=d.id,mid=d.order_material_id;
                var stallId = $("#stall-ids-"+id).val();
                var stallFeedType = d.stall_feed_type;
                var caigouUnitprice = d.caigou_unitprice;
                var billingCaigouKgprice = d.billing_caigou_kgprice;
                var stallOrderTime=$("#stall_order_time"+id).val();
                var stallOrder=d.stall_order;
                var billingCaigouCountFeed=d.billing_caigou_count_feed;
                var billingCaigouKgcount=d.billing_caigou_kgcount;//开单采购公斤数
                if(!checkData(d)) return;
                $.ajax({
                   type: "POST",
                   url: "{:url('StallFeed/stallFeedConfirm')}",
                   data: {
                       id:id,
                       stall_order_time:stallOrderTime,
                       caigou_unitprice:caigouUnitprice,
                       billing_caigou_kgprice:billingCaigouKgprice,
                       billing_caigou_kgcount:billingCaigouKgcount,
                       stall_feed_type:stallFeedType,
                       stall_id:stallId,
                       stall_order:stallOrder,
                       billing_caigou_count_feed:billingCaigouCountFeed
                   },
                   dataType:"json",
                   success: function(res){
                      if (res.code == 1) {
                         $('.subbtn-'+id).addClass('layui-btn-normal');
                         $('.subbtn-'+id).html('修改');console.log(res)
                         $('.billingCaigouCount-'+mid, parent.document).html(res.data.billing_caigou_count);
                         $('.caigouSubtotal-'+mid, parent.document).html(res.data.caigou_subtotal_money);
                         $('.caigou-total-money-'+res.data.order_id, parent.document).html(res.data.caigou_total_money);
                         parent.layui.layer.closeAll();
                         layer.msg(res.msg, {icon: 1});
                      } else {
                         layer.msg(res.msg, {icon: 2,anim: 6});
                      }
                   }
                });
            }           	
            
        });
        // 单元格修改数据校验
		window.checkData = function(d) {
			var caigouUnitprice = d.caigou_unitprice;
        	var billingCaigouKgprice = d.billing_caigou_kgprice;
            var stallFeedType = d.stall_feed_type;
        	
        	var reg = /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/;
        	if (!reg.test(caigouUnitprice)) {
        		layer.msg('采购单价输入有误', {icon: 2,anim: 6});
        		return false;
        	}
        	if (!reg.test(billingCaigouKgprice)) {
        		layer.msg('开单采购公斤价输入有误', {icon: 2,anim: 6});
        		return false;
        	}
//            if (stallFeedType=="") {
//        		layer.msg('退补类型不能为空', {icon: 2,anim: 6});
//        		return false;
//        	}
        	return true;
		}
        // 补料
		window.feedEvent = function(number, mid) {
			//var reg = /((^[1-9]\d*)|^0)(\.\d{0,2}){0,1}$/;
			//if(reg.test(number)) {
            var billingCaigouKgcount=$('.billing-caigou-kgcount').val();
				$.ajax({
			 		   type: "POST",
			 		   url: "{:url('costFeed')}",
			 		   data: "mid="+mid+"&number="+number+"&billing_caigou_kgcount="+billingCaigouKgcount,
			 		   dataType:"json",
			 		   success: function(res){
			 			  if (res.code == 1) {
                            table.reload('dataTable');
                            var ori = $('.feed-detail-'+mid, parent.document).html();
			 				var newFeed = ori=='' ? number : (ori+(number>0?"+"+Math.abs(number):number));
			 				$('.feed-detail-'+mid, parent.document).html(newFeed);
                            $('.billingCaigou-'+mid, parent.document).html(res.data.billing_caigou_count);
                            $('.caigouSubtotal-'+mid, parent.document).html(res.data.caigou_subtotal_money);
			 				$('.caigou-total-money-'+res.data.order_id, parent.document).html(res.data.caigou_total_money);
							layer.msg(res.msg, {icon: 1});
							parent.reloadTable();
							layer.closeAll();
                           // parent.layui.layer.closeAll();
						  } else {
							 layer.msg(res.msg, {icon: 2,anim: 6});
						  }
			 		   }
			 		});
			//} else layer.msg('数量填写有误', {icon: 2,anim: 6});
		};
    });
</script>